/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.boot.util;

import cn.hutool.core.text.CharSequenceUtil;
import com.iwindplus.boot.domain.constant.CommonConstant;
import com.iwindplus.boot.domain.constant.CommonConstant.ExceptionConstant;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ReflectionUtils;

/**
 * 校验对象属性是否全部为空工具类.
 *
 * @author zengdegui
 * @since 2021/11/23
 */
@Slf4j
public class ObjectIsNullUtil {
    private ObjectIsNullUtil() {
        throw new IllegalStateException(CommonConstant.UTILITY_CLASS);
    }

    /**
     * 验证字段是否全部为空.
     *
     * @param obj 对象
     * @return boolean
     */
    public static boolean isAllFieldNull(Object obj) {
        try {
            for (Field f : obj.getClass().getDeclaredFields()) {
                ReflectionUtils.makeAccessible(f);
                if (Modifier.isFinal(f.getModifiers()) && Modifier.isStatic(f.getModifiers())) {
                    continue;
                }
                if (!isEmpty(f.get(obj))) {
                    return false;
                }
            }
        } catch (IllegalAccessException ex) {
            log.error(ExceptionConstant.ILLEGAL_ACCESS_EXCEPTION, ex);
        }
        return true;
    }

    private static boolean isEmpty(Object obj) {
        if (Objects.isNull(obj)) {
            return true;
        } else {
            if (obj instanceof String param && CharSequenceUtil.isBlank(param)) {
                return true;
            }
            if (obj instanceof Collection<?> param && param.isEmpty()) {
                return true;
            }
            if (obj instanceof Map<?, ?> param && param.isEmpty()) {
                return true;
            }
            if (obj instanceof Object[] param && param.length == 0) {
                return true;
            }
        }
        return false;
    }
}
